﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;

namespace EFTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //TestEt();
            //TestET2();
            Database.SetInitializer<ProductContext>(new DropCreateDatabaseIfModelChanges<ProductContext>());
            TestET2();
        }

        public void TestEt()
        {
            using(var db = new ProductContext())   
            {       // Add a food category     
                var food = new Category { CategoryId = "FOOD", Name = "Foods" };      
                db.Categories.Add(food);     
                int recordsAffected = db.SaveChanges();     
              

            } 
        }

        public void TestET2()
        {
            using (var db = new ProductContext())
            {
                var food = db.Categories.Find("FOOD");
                if (food == null)
                {
                    food = new Category { CategoryId = "FOOD", Name = "Foods" };
                    db.Categories.Add(food); 
                }

                var product = new Product() {  Category=food, Name="banana1"};
                db.Products.Add(product);
                int records = db.SaveChanges();

                var allfood = from p in db.Products
                              where p.CategoryId == "FOOD"
                              orderby p.Name
                              select p;
                foreach (var item in allfood)
                {
                    Response.Write(string.Format("  {0}", item.Name));
                }
                                    
            }
        }
    }
}
